<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />

<meta name="keywords" content="Go,CSS3,CSS,弹性盒子,版本管理,SASS,windows,安装,系统,编程工具,标记语言,YAML,文章编辑," />


  <meta name="keywords" content="Go," />
  






  <meta name="description" content="[Go Web编程]-Go函数">



  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/01/16/02.3.1/"/>




<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?53c9f3c831c566994310092f43b59abf";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

  <title> [Go Web编程]-Go函数 | 土豆的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">土豆的博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">一个web工程师的博客</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">×</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/01/16/02.3.1/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="土豆">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/user.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="土豆的博客">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="土豆的博客" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                [Go Web编程]-Go函数
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-01-16T09:23:53+08:00">
                2017-01-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Go/" itemprop="url" rel="index">
                    <span itemprop="name">Go</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>函数是Go里面的核心设计<a id="more"></a>，它通过关键字<code>func</code>来声明，它的格式如下：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">funcName</span><span class="params">(input1 type1, input2 type2)</span> <span class="params">(output1 type1, output2 type2)</span></span> &#123;</div><div class="line">	<span class="comment">//这里是处理逻辑代码</span></div><div class="line">	<span class="comment">//返回多个值</span></div><div class="line">	<span class="keyword">return</span> value1, value2</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>上面的代码我们看出</p>
<ul>
<li>关键字<code>func</code>用来声明一个函数<code>funcName</code></li>
<li>函数可以有一个或者多个参数，每个参数后面带有类型，通过<code>,</code>分隔</li>
<li>函数可以返回多个值</li>
<li>上面返回值声明了两个变量<code>output1</code>和<code>output2</code>，如果你不想声明也可以，直接就两个类型</li>
<li>如果只有一个返回值且不声明返回值变量，那么你可以省略 包括返回值 的括号</li>
<li>如果没有返回值，那么就直接省略最后的返回信息</li>
<li>如果有返回值， 那么必须在函数的外层添加return语句</li>
</ul>
<p>下面我们来看一个实际应用函数的例子（用来计算Max值）<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"></div><div class="line"><span class="comment">// 返回a、b中最大值.</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">max</span><span class="params">(a, b <span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123;</div><div class="line">	<span class="keyword">if</span> a &gt; b &#123;</div><div class="line">		<span class="keyword">return</span> a</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> b</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">	x := <span class="number">3</span></div><div class="line">	y := <span class="number">4</span></div><div class="line">	z := <span class="number">5</span></div><div class="line"></div><div class="line">	max_xy := max(x, y) <span class="comment">//调用函数max(x, y)</span></div><div class="line">	max_xz := max(x, z) <span class="comment">//调用函数max(x, z)</span></div><div class="line"></div><div class="line">	fmt.Printf(<span class="string">"max(%d, %d) = %d\n"</span>, x, y, max_xy)</div><div class="line">	fmt.Printf(<span class="string">"max(%d, %d) = %d\n"</span>, x, z, max_xz)</div><div class="line">	fmt.Printf(<span class="string">"max(%d, %d) = %d\n"</span>, y, z, max(y,z)) <span class="comment">// 也可在这直接调用它</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>上面这个里面我们可以看到<code>max</code>函数有两个参数，它们的类型都是<code>int</code>，那么第一个变量的类型可以省略（即 a,b int,而非 a int, b int)，默认为离它最近的类型，同理多于2个同类型的变量或者返回值。同时我们注意到它的返回值就是一个类型，这个就是省略写法。</p>
<h3 id="多个返回值"><a href="#多个返回值" class="headerlink" title="多个返回值"></a>多个返回值</h3><p>Go语言比C更先进的特性，其中一点就是函数能够返回多个值。</p>
<p>我们直接上代码看例子<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"></div><div class="line"><span class="comment">//返回 A+B 和 A*B</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">SumAndProduct</span><span class="params">(A, B <span class="keyword">int</span>)</span> <span class="params">(<span class="keyword">int</span>, <span class="keyword">int</span>)</span></span> &#123;</div><div class="line">	<span class="keyword">return</span> A+B, A*B</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">	x := <span class="number">3</span></div><div class="line">	y := <span class="number">4</span></div><div class="line"></div><div class="line">	xPLUSy, xTIMESy := SumAndProduct(x, y)</div><div class="line"></div><div class="line">	fmt.Printf(<span class="string">"%d + %d = %d\n"</span>, x, y, xPLUSy)</div><div class="line">	fmt.Printf(<span class="string">"%d * %d = %d\n"</span>, x, y, xTIMESy)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>上面的例子我们可以看到直接返回了两个参数，当然我们也可以命名返回参数的变量，这个例子里面只是用了两个类型，我们也可以改成如下这样的定义，然后返回的时候不用带上变量名，因为直接在函数里面初始化了。但如果你的函数是导出的(首字母大写)，官方建议：最好命名返回值，因为不命名返回值，虽然使得代码更加简洁了，但是会造成生成的文档可读性差。<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">SumAndProduct</span><span class="params">(A, B <span class="keyword">int</span>)</span> <span class="params">(add <span class="keyword">int</span>, Multiplied <span class="keyword">int</span>)</span></span> &#123;</div><div class="line">	add = A+B</div><div class="line">	Multiplied = A*B</div><div class="line">	<span class="keyword">return</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="变参"><a href="#变参" class="headerlink" title="变参"></a>变参</h3><p>Go函数支持变参。接受变参的函数是有着不定数量的参数的。为了做到这点，首先需要定义函数使其接受变参：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">myfunc</span><span class="params">(arg ...<span class="keyword">int</span>)</span></span> &#123;&#125;</div></pre></td></tr></table></figure></p>
<p><code>arg ...int</code>告诉Go这个函数接受不定数量的参数。注意，这些参数的类型全部是<code>int</code>。在函数体中，变量<code>arg</code>是一个<code>int</code>的<code>slice</code>：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">for</span> _, n := <span class="keyword">range</span> arg &#123;</div><div class="line">	fmt.Printf(<span class="string">"And the number is: %d\n"</span>, n)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="传值与传指针"><a href="#传值与传指针" class="headerlink" title="传值与传指针"></a>传值与传指针</h3><p>当我们传一个参数值到被调用函数里面时，实际上是传了这个值的一份copy，当在被调用函数中修改参数值的时候，调用函数中相应实参不会发生任何变化，因为数值变化只作用在copy上。</p>
<p>为了验证我们上面的说法，我们来看一个例子<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"></div><div class="line"><span class="comment">//简单的一个函数，实现了参数+1的操作</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">add1</span><span class="params">(a <span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123;</div><div class="line">	a = a+<span class="number">1</span> <span class="comment">// 我们改变了a的值</span></div><div class="line">	<span class="keyword">return</span> a <span class="comment">//返回一个新值</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">	x := <span class="number">3</span></div><div class="line"></div><div class="line">	fmt.Println(<span class="string">"x = "</span>, x)  <span class="comment">// 应该输出 "x = 3"</span></div><div class="line"></div><div class="line">	x1 := add1(x)  <span class="comment">//调用add1(x)</span></div><div class="line"></div><div class="line">	fmt.Println(<span class="string">"x+1 = "</span>, x1) <span class="comment">// 应该输出"x+1 = 4"</span></div><div class="line">	fmt.Println(<span class="string">"x = "</span>, x)    <span class="comment">// 应该输出"x = 3"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>看到了吗？虽然我们调用了<code>add1</code>函数，并且在<code>add1</code>中执行<code>a = a+1</code>操作，但是上面例子中<code>x</code>变量的值没有发生变化</p>
<p>理由很简单：因为当我们调用<code>add1</code>的时候，<code>add1</code>接收的参数其实是<code>x</code>的copy，而不是<code>x</code>本身。</p>
<p>那你也许会问了，如果真的需要传这个<code>x</code>本身,该怎么办呢？</p>
<p>这就牵扯到了所谓的指针。我们知道，变量在内存中是存放于一定地址上的，修改变量实际是修改变量地址处的内存。只有<code>add1</code>函数知道<code>x</code>变量所在的地址，才能修改<code>x</code>变量的值。所以我们需要将<code>x</code>所在地址<code>&amp;x</code>传入函数，并将函数的参数的类型由<code>int</code>改为<code>*int</code>，即改为指针类型，才能在函数中修改<code>x</code>变量的值。此时参数仍然是按copy传递的，只是copy的是一个指针。请看下面的例子<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"></div><div class="line"><span class="comment">//简单的一个函数，实现了参数+1的操作</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">add1</span><span class="params">(a *<span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123; <span class="comment">// 请注意，</span></div><div class="line">	*a = *a+<span class="number">1</span> <span class="comment">// 修改了a的值</span></div><div class="line">	<span class="keyword">return</span> *a <span class="comment">// 返回新值</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">	x := <span class="number">3</span></div><div class="line"></div><div class="line">	fmt.Println(<span class="string">"x = "</span>, x)  <span class="comment">// 应该输出 "x = 3"</span></div><div class="line"></div><div class="line">	x1 := add1(&amp;x)  <span class="comment">// 调用 add1(&amp;x) 传x的地址</span></div><div class="line"></div><div class="line">	fmt.Println(<span class="string">"x+1 = "</span>, x1) <span class="comment">// 应该输出 "x+1 = 4"</span></div><div class="line">	fmt.Println(<span class="string">"x = "</span>, x)    <span class="comment">// 应该输出 "x = 4"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这样，我们就达到了修改<code>x</code>的目的。那么到底传指针有什么好处呢？</p>
<ul>
<li>传指针使得多个函数能操作同一个对象。</li>
<li>传指针比较轻量级 (8bytes),只是传内存地址，我们可以用指针传递体积大的结构体。如果用参数值传递的话, 在每次copy上面就会花费相对较多的系统开销（内存和时间）。所以当你要传递大的结构体的时候，用指针是一个明智的选择。</li>
<li>Go语言中<code>channel</code>，<code>slice</code>，<code>map</code>这三种类型的实现机制类似指针，所以可以直接传递，而不用取地址后传递指针。（注：若函数需改变<code>slice</code>的长度，则仍需要取地址传递指针）</li>
</ul>
<h3 id="defer"><a href="#defer" class="headerlink" title="defer"></a>defer</h3><p>Go语言中有种不错的设计，即延迟（defer）语句，你可以在函数中添加多个defer语句。当函数执行到最后时，这些defer语句会按照逆序执行，最后该函数返回。特别是当你在进行一些打开资源的操作时，遇到错误需要提前返回，在返回前你需要关闭相应的资源，不然很容易造成资源泄露等问题。如下代码所示，我们一般写打开一个资源是这样操作的：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">ReadWrite</span><span class="params">()</span> <span class="title">bool</span></span> &#123;</div><div class="line">	file.Open(<span class="string">"file"</span>)</div><div class="line"><span class="comment">// 做一些工作</span></div><div class="line">	<span class="keyword">if</span> failureX &#123;</div><div class="line">		file.Close()</div><div class="line">		<span class="keyword">return</span> <span class="literal">false</span></div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="keyword">if</span> failureY &#123;</div><div class="line">		file.Close()</div><div class="line">		<span class="keyword">return</span> <span class="literal">false</span></div><div class="line">	&#125;</div><div class="line"></div><div class="line">	file.Close()</div><div class="line">	<span class="keyword">return</span> <span class="literal">true</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>我们看到上面有很多重复的代码，Go的<code>defer</code>有效解决了这个问题。使用它后，不但代码量减少了很多，而且程序变得更优雅。在<code>defer</code>后指定的函数会在函数退出前调用。<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">ReadWrite</span><span class="params">()</span> <span class="title">bool</span></span> &#123;</div><div class="line">	file.Open(<span class="string">"file"</span>)</div><div class="line">	<span class="keyword">defer</span> file.Close()</div><div class="line">	<span class="keyword">if</span> failureX &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">false</span></div><div class="line">	&#125;</div><div class="line">	<span class="keyword">if</span> failureY &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">false</span></div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> <span class="literal">true</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>如果有很多调用<code>defer</code>，那么<code>defer</code>是采用后进先出模式，所以如下代码会输出<code>4 3 2 1 0</code><br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">5</span>; i++ &#123;</div><div class="line">	<span class="keyword">defer</span> fmt.Printf(<span class="string">"%d "</span>, i)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="函数作为值、类型"><a href="#函数作为值、类型" class="headerlink" title="函数作为值、类型"></a>函数作为值、类型</h3><p>在Go中函数也是一种变量，我们可以通过<code>type</code>来定义它，它的类型就是所有拥有相同的参数，相同的返回值的一种类型</p>
<pre><code>type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
</code></pre><p>函数作为类型到底有什么好处呢？那就是可以把这个类型的函数当做值来传递，请看下面的例子<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"></div><div class="line"><span class="keyword">type</span> testInt <span class="function"><span class="keyword">func</span><span class="params">(<span class="keyword">int</span>)</span> <span class="title">bool</span> // 声明了一个函数类型</span></div><div class="line"></div><div class="line"><span class="title">func</span> <span class="title">isOdd</span><span class="params">(integer <span class="keyword">int</span>)</span> <span class="title">bool</span> &#123;</div><div class="line">	<span class="keyword">if</span> integer%<span class="number">2</span> == <span class="number">0</span> &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">false</span></div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> <span class="literal">true</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">isEven</span><span class="params">(integer <span class="keyword">int</span>)</span> <span class="title">bool</span></span> &#123;</div><div class="line">	<span class="keyword">if</span> integer%<span class="number">2</span> == <span class="number">0</span> &#123;</div><div class="line">		<span class="keyword">return</span> <span class="literal">true</span></div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> <span class="literal">false</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 声明的函数类型在这个地方当做了一个参数</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">filter</span><span class="params">(slice []<span class="keyword">int</span>, f testInt)</span> []<span class="title">int</span></span> &#123;</div><div class="line">	<span class="keyword">var</span> result []<span class="keyword">int</span></div><div class="line">	<span class="keyword">for</span> _, value := <span class="keyword">range</span> slice &#123;</div><div class="line">		<span class="keyword">if</span> f(value) &#123;</div><div class="line">			result = <span class="built_in">append</span>(result, value)</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> result</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</div><div class="line">	slice := []<span class="keyword">int</span> &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">7</span>&#125;</div><div class="line">	fmt.Println(<span class="string">"slice = "</span>, slice)</div><div class="line">	odd := filter(slice, isOdd)    <span class="comment">// 函数当做值来传递了</span></div><div class="line">	fmt.Println(<span class="string">"Odd elements of slice are: "</span>, odd)</div><div class="line">	even := filter(slice, isEven)  <span class="comment">// 函数当做值来传递了</span></div><div class="line">	fmt.Println(<span class="string">"Even elements of slice are: "</span>, even)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>函数当做值和类型在我们写一些通用接口的时候非常有用，通过上面例子我们看到<code>testInt</code>这个类型是一个函数类型，然后两个<code>filter</code>函数的参数和返回值与<code>testInt</code>类型是一样的，但是我们可以实现很多种的逻辑，这样使得我们的程序变得非常的灵活。</p>
<h3 id="Panic和Recover"><a href="#Panic和Recover" class="headerlink" title="Panic和Recover"></a>Panic和Recover</h3><p>Go没有像Java那样的异常机制，它不能抛出异常，而是使用了<code>panic</code>和<code>recover</code>机制。一定要记住，你应当把它作为最后的手段来使用，也就是说，你的代码中应当没有，或者很少有<code>panic</code>的东西。这是个强大的工具，请明智地使用它。那么，我们应该如何使用它呢？</p>
<p>Panic</p>
<blockquote>
<p>是一个内建函数，可以中断原有的控制流程，进入一个令人恐慌的流程中。当函数<code>F</code>调用<code>panic</code>，函数F的执行被中断，但是<code>F</code>中的延迟函数会正常执行，然后F返回到调用它的地方。在调用的地方，<code>F</code>的行为就像调用了<code>panic</code>。这一过程继续向上，直到发生<code>panic</code>的<code>goroutine</code>中所有调用的函数返回，此时程序退出。恐慌可以直接调用<code>panic</code>产生。也可以由运行时错误产生，例如访问越界的数组。</p>
</blockquote>
<p>Recover</p>
<blockquote>
<p>是一个内建的函数，可以让进入令人恐慌的流程中的<code>goroutine</code>恢复过来。<code>recover</code>仅在延迟函数中有效。在正常的执行过程中，调用<code>recover</code>会返回<code>nil</code>，并且没有其它任何效果。如果当前的<code>goroutine</code>陷入恐慌，调用<code>recover</code>可以捕获到<code>panic</code>的输入值，并且恢复正常的执行。</p>
</blockquote>
<p>下面这个函数演示了如何在过程中使用<code>panic</code><br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">var</span> user = os.Getenv(<span class="string">"USER"</span>)</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">init</span><span class="params">()</span></span> &#123;</div><div class="line">	<span class="keyword">if</span> user == <span class="string">""</span> &#123;</div><div class="line">		<span class="built_in">panic</span>(<span class="string">"no value for $USER"</span>)</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>下面这个函数检查作为其参数的函数在执行时是否会产生<code>panic</code>：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">throwsPanic</span><span class="params">(f <span class="keyword">func</span>()</span>) <span class="params">(b <span class="keyword">bool</span>)</span></span> &#123;</div><div class="line">	<span class="keyword">defer</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</div><div class="line">		<span class="keyword">if</span> x := <span class="built_in">recover</span>(); x != <span class="literal">nil</span> &#123;</div><div class="line">			b = <span class="literal">true</span></div><div class="line">		&#125;</div><div class="line">	&#125;()</div><div class="line">	f() <span class="comment">//执行函数f，如果f中出现了panic，那么就可以恢复回来</span></div><div class="line">	<span class="keyword">return</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="main函数和init函数"><a href="#main函数和init函数" class="headerlink" title="main函数和init函数"></a><code>main</code>函数和<code>init</code>函数</h3><p>Go里面有两个保留的函数：<code>init</code>函数（能够应用于所有的<code>package</code>）和<code>main</code>函数（只能应用于<code>package main</code>）。这两个函数在定义时不能有任何的参数和返回值。虽然一个<code>package</code>里面可以写任意多个<code>init</code>函数，但这无论是对于可读性还是以后的可维护性来说，我们都强烈建议用户在一个<code>package</code>中每个文件只写一个<code>init</code>函数。</p>
<p>Go程序会自动调用<code>init()</code>和<code>main()</code>，所以你不需要在任何地方调用这两个函数。每个<code>package</code>中的<code>init</code>函数都是可选的，但<code>package main</code>就必须包含一个<code>main</code>函数。</p>
<p>程序的初始化和执行都起始于<code>main</code>包。如果<code>main</code>包还导入了其它的包，那么就会在编译时将它们依次导入。有时一个包会被多个包同时导入，那么它只会被导入一次（例如很多包可能都会用到<code>fmt</code>包，但它只会被导入一次，因为没有必要导入多次）。当一个包被导入时，如果该包还导入了其它的包，那么会先将其它包导入进来，然后再对这些包中的包级常量和变量进行初始化，接着执行<code>init</code>函数（如果有的话），依次类推。等所有被导入的包都加载完毕了，就会开始对<code>main</code>包中的包级常量和变量进行初始化，然后执行<code>main</code>包中的<code>init</code>函数（如果存在的话），最后执行<code>main</code>函数。下图详细地解释了整个执行过程：</p>
<p><img src="images/2.3.init.png?raw=true" alt=""></p>
<p>图2.6 main函数引入包初始化流程图</p>
<h3 id="import"><a href="#import" class="headerlink" title="import"></a>import</h3><p>我们在写Go代码的时候经常用到import这个命令用来导入包文件，而我们经常看到的方式参考如下：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">import</span>(</div><div class="line">    <span class="string">"fmt"</span></div><div class="line">)</div></pre></td></tr></table></figure></p>
<p>然后我们代码里面可以通过如下的方式调用<br><figure class="highlight go"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">fmt.Println(<span class="string">"hello world"</span>)</div></pre></td></tr></table></figure></p>
<p>上面这个fmt是Go语言的标准库，其实是去<code>GOROOT</code>环境变量指定目录下去加载该模块，当然Go的import还支持如下两种方式来加载自己写的模块：</p>
<ol>
<li><p>相对路径</p>
<p> import “./model” //当前文件同一目录的model目录，但是不建议这种方式来import</p>
</li>
<li><p>绝对路径</p>
<p> import “shorturl/model” //加载gopath/src/shorturl/model模块</p>
</li>
</ol>
<p>上面展示了一些import常用的几种方式，但是还有一些特殊的import，让很多新手很费解，下面我们来一一讲解一下到底是怎么一回事</p>
<ol>
<li><p>点操作</p>
<p> 我们有时候会看到如下的方式导入包</p>
<pre><code>import(
    . &quot;fmt&quot;
)
</code></pre><p> 这个点操作的含义就是这个包导入之后在你调用这个包的函数时，你可以省略前缀的包名，也就是前面你调用的fmt.Println(“hello world”)可以省略的写成Println(“hello world”)</p>
</li>
<li><p>别名操作</p>
<p> 别名操作顾名思义我们可以把包命名成另一个我们用起来容易记忆的名字</p>
<pre><code>import(
    f &quot;fmt&quot;
)
</code></pre><p> 别名操作的话调用包函数时前缀变成了我们的前缀，即f.Println(“hello world”)</p>
</li>
<li><p>_操作</p>
<p> 这个操作经常是让很多人费解的一个操作符，请看下面这个import</p>
<pre><code class="Go">
<span class="keyword">import</span> (
    <span class="string">"database/sql"</span>
    _ <span class="string">"github.com/ziutek/mymysql/godrv"</span>
)
</code></pre>
<p> _操作其实是引入该包，而不直接使用包里面的函数，而是调用了该包里面的init函数。</p>
</li>
</ol>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Go/" rel="tag"># Go</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/15/02.3/" rel="next" title="[Go Web编程]-Go流程控制">
                <i class="fa fa-chevron-left"></i> [Go Web编程]-Go流程控制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/user.jpg"
               alt="土豆" />
          <p class="site-author-name" itemprop="name">土豆</p>
          <p class="site-description motion-element" itemprop="description">学习和整理web技术，方面自己查阅，也希望方便他人</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">13</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#多个返回值"><span class="nav-number">1.</span> <span class="nav-text">多个返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#变参"><span class="nav-number">2.</span> <span class="nav-text">变参</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#传值与传指针"><span class="nav-number">3.</span> <span class="nav-text">传值与传指针</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#defer"><span class="nav-number">4.</span> <span class="nav-text">defer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数作为值、类型"><span class="nav-number">5.</span> <span class="nav-text">函数作为值、类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Panic和Recover"><span class="nav-number">6.</span> <span class="nav-text">Panic和Recover</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#main函数和init函数"><span class="nav-number">7.</span> <span class="nav-text">main函数和init函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#import"><span class="nav-number">8.</span> <span class="nav-text">import</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土豆</span>
</div>


<!--

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

-->

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  


</body>
</html>
